<template>
	<view class="flex flex-col h-full" style="align-items: stretch;overflow: hidden;">
		<div class="fixed">
			<div class="between p-30">
				<div class="flex shadow  bg-white h-70 rounded-35 flex-1">
					<image src="/static/icon/search.png" mode="widthFix" class="w-30 flex-shirnk-0 ml-20"></image>
					<input type="text" placeholder="请输入电站名或地区" class="flex-1 ml-20" v-model="keyword">
					<div class="text-orange mr-20 pl-20 fz32" style="border-left: 1px solid #FF8F1F;" @click="search()">
						搜索</div>
				</div>

			</div>
			<div class="between pl-30 pr-30" v-if="history.length > 0">
				<div class="flex">
					<image src="/static/icon/history.png" mode="widthFix" class="w-40"></image>
					<div class="font-bold text-gray-900 ml-10">最近搜索</div>
				</div>
				<image src="/static/icon/del.png" mode="widthFix" class="w-40" @click="clearHistory()"></image>
			</div>
			<div class="pl-30 pr-30">
				<div class="flex flex-wrap">
					<div class="fz32 rounded-30 pt-5 pb-5 pl-20 pr-20 bg-gray-400 text-white mr-20 mt-20"
						v-for="item in history" @click="keyword = item; search()">{{ item }}</div>
				</div>
			</div>
		</div>
		<scroll-view scroll-y="true" class="h-full">
			<div class="p-30">
				<Station v-for="item in stations" :key="item.id" :item="item" class="mb-20" />
				<!-- <Lot lass="mb-20" /> -->
				<!-- <Pile lass="mb-20" /> -->
			</div>
		</scroll-view>
	</view>
</template>

<script>
import Station from "@/components/common/Station.vue"
import Lot from "@/components/common/Lot.vue"
import Pile from "@/components/common/Pile.vue"
export default {
	components: {
		Station,
		Pile,
		Lot
	},
	onLoad(options) {
		this.keyword = options.keyword
		uni.getLocation({
			type: 'wgs84',
			success: (res) => {
				this.lat = res.latitude
				this.lng = res.longitude
				this.search()
			},
			fail: (e) => {
				this.search()
			}
		})
	},
	data() {
		return {
			keyword: '',
			lat:'',
			lng:'',
			stations: [],
			history: []
		}
	},
	methods: {
		clearHistory() {
			uni.removeStorageSync('search_history')
			this.history = []
		},
		async search() {

			// 从缓存获取历史搜索记录
			let history = uni.getStorageSync('search_history') || []
			// 如果有关键词且不在历史记录中,添加到开头
			if (this.keyword && !history.includes(this.keyword)) {
				history.unshift(this.keyword)
				// 只保留最近10条
				if (history.length > 10) {
					history = history.slice(0, 10)
				}
				// 保存到缓存
				uni.setStorageSync('search_history', history)
			}
			this.history = uni.getStorageSync('search_history')

			const res = await this.http("get", '/api/station/index', {
				keyword: this.keyword,lat:this.lat,lng:this.lng
			})
			if (res.code == 200) {
				this.stations = res.data
			}
		}
	}
}
</script>

<style>
page {
	height: 100%;
	overflow: hidden;
}
</style>